<template>
  <el-card>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      inline
    >
      <el-form-item label="作者：">
        <span class="el-input">{{ form.author }}</span>
      </el-form-item>
      <el-form-item label="标题：" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="描述：" prop="desc">
        <el-input v-model="form.desc" type="textarea"></el-input>
      </el-form-item>

      <el-form-item label="分类：" prop="category">
        <el-select v-model="form.category" placeholder="请选择属于分类">
          <el-option
            v-for="item in categories"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签：" prop="tags">
        <el-select v-model="form.tags" multiple placeholder="请选择标签">
          <el-option
            v-for="item in tagList"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="keyword" label="关键字：">
        <el-input v-model="form.keyword" placeholder="请输入关键字"></el-input>
      </el-form-item>
      <el-form-item label="文章类型：">
        <el-select v-model="form.type" placeholder="请选择文章类型">
          <el-option label="普通文章" value="1"></el-option>
          <el-option label="简历" value="2"></el-option>
          <el-option label="管理员介绍" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="转载状态：">
        <el-select v-model="form.origin" placeholder="请选择转载状态">
          <el-option label="原创" value="0"></el-option>
          <el-option label="转载" value="1"></el-option>
          <el-option label="混合" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="image_uri" label="封面：">
        <el-row type="flex" justify="space-between">
          <el-col>
            <div
              class="el-input__inner upload-image"
              :class="{ 'el-upload-list--picture-card': form.image_uri }"
            >
              <template v-if="form.image_uri">
                <img :src="form.image_uri" width="100%" height="100%" />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="dialogVisible = true"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    class="el-upload-list__item-delete"
                    @click="handleRemove"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </template>
            </div>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="form.image_uri" alt="" />
            </el-dialog>
          </el-col>
          <el-col>
            <el-upload
              style="display: inline-block"
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handlePicChange"
              :before-upload="beforeAvatarUpload"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="是否开源：">
        <el-radio-group v-model="form.secret">
          <el-radio label="0">公开</el-radio>
          <el-radio label="1">私密</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- <el-form-item label="内容："> -->
      <markdown-editor v-model="form.content" />
      <!-- </el-form-item> -->
      <div class="mgtb30 tc">
        <el-button type="info" @click="save">存为草稿</el-button>
        <el-button type="primary" @click="handleSubmit">发表文章</el-button>
      </div>
    </el-form>
  </el-card>
</template>
<script>
import MarkdownEditor from '@/components/MarkdownEditor'
import { addArticle } from '@/api/article'
import { getAllCategory } from '@/api/category'
import { getAllTag } from '@/api/tag'

import { mapGetters } from 'vuex'
export default {
  components: { MarkdownEditor },
  data() {
    return {
      dialogVisible: false,
      form: {
        title: '', // 文章标题
        desc: '', // 描述
        author: '', // 作者
        category: '', // 分类
        tags: [], // 标签
        image_uri: '',
        articleImg: '',
        type: '1',
        origin: '0',
        // createTime: new Date(), // 创建时间
        secret: '2', // 是否开源
        content: '' // 文章内容
      },
      categories: [], // 分类
      tagList: [], // 标签
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入文章描述', trigger: 'blur' }],
        author: [{ required: true, message: '请选择作者', trigger: 'change' }],
        category: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        tags: [{ required: true, message: '请选择标签', trigger: 'change' }],
        // createTime: [
        //   { required: true, message: '请选择创建时间', trigger: 'change' }
        // ],
        secret: [
          { required: true, message: '请选择是否开源', trigger: 'change' }
        ]
        // image_uri: [
        //   { required: true, message: '请输入封面地址', trigger: 'change' }
        // ]
      }
    }
  },
  created() {
    this.form.author = this.nickName
  },
  mounted() {
    this.getCategory() // 获取分类列表
    this.getTags() // 获取标签列表
  },
  computed: {
    ...mapGetters(['nickName'])
  },
  methods: {
    async getCategory() {
      const { _RejCode, data } = await getAllCategory().catch((err) => err)
      if (_RejCode !== '00000000') return
      this.categories = data.list
    },
    async getTags() {
      const { _RejCode, data } = await getAllTag().catch((err) => err)
      if (_RejCode !== '00000000') return
      this.tagList = data.list
    },
    handlePicChange(file) {
      this.form.image_uri = URL.createObjectURL(file.raw)
      this.form.articleImg = file.raw
    },
    handleRemove() {
      this.form.image_uri = ''
      this.form.articleImg = ''
    },
    //限制上传时的文件格式大小
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 3
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 和 Png 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 3MB!')
        return false
      }
    },
    save() {
      this.form.state = 0
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          const formData = new FormData()
          for (let [key, value] of Object.entries(this.form)) {
            formData.append(key, value)
          }
          const { _RejCode, _RejMsg } = await addArticle(formData)
          if (_RejCode !== '00000000') return
          this.$message.success(_RejMsg)
        }
      })
    },
    handleSubmit() {
      this.form.state = 1
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          const formData = new FormData()
          for (let [key, value] of Object.entries(this.form)) {
            formData.append(key, value)
          }
          const { _RejCode, _RejMsg } = await addArticle(formData)
          if (_RejCode !== '00000000') return
          this.$message.success(_RejMsg)
          // this.$router.push('/article/list')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
  .el-radio-group,
  .el-textarea,
  .el-input {
    width: 280px;
  }
  .el-select {
    width: 280px;
    & > .el-input {
      width: 100%;
    }
  }
}
.upload-image {
  width: 172px;
  margin-right: 10px;
  height: 40px;
  padding: 0;
  position: relative;
}
.el-row {
  height: 40px;
}
</style>
